package com.suishoupai.xmb.controller;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.suishoupai.xmb.entity.*;
import com.suishoupai.xmb.exception.XmbException;
import com.suishoupai.xmb.service.*;
import com.suishoupai.xmb.utils.PageUtil;
import com.suishoupai.xmb.utils.SecurityUserUtil;
import com.suishoupai.xmb.utils.ValidateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


/**
 * Created by caojian on 2017/3/22.
 */
@Controller
@RequestMapping("/sale")
public class UserSaleController {
    private static final Log LOG = LogFactory.getLog(UserSaleController.class);

    @Autowired
    private UserSaleService userSaleService;
    @Autowired
    private AuthService authService;
    @Autowired
    private QiniuService qiniuService;
    @Autowired
    private UserService userService;
    @Autowired
    private DeliveryDiscountService deliveryDiscountService;

    /**
     * 管理员查看卖家列表
     *
     * @param model
     * @return
     */
    @GetMapping("")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public String list(@RequestParam Map map, Model model) {
        PageUtil.startPage(map);
        Page page = (Page) userSaleService.getAllSale();
        model.addAttribute("sales", page.toPageInfo());
        return "sale-list";
    }

    /**
     * 管理员增加卖家页面
     */
    @GetMapping("/add")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public String addPage(@ModelAttribute("message") String message, Model model) {
        model.addAttribute("message", message);
        return "sale-add";
    }

    /**
     * 管理员增加卖家(发送一封邮件，让用户自己激活)
     *
     * @return
     */
    @PostMapping("")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Object add(String email, RedirectAttributes model) {
        ValidateUtil.isEmail(email);
        try {
            authService.addActivation(email);
        } catch (XmbException e) {
            model.addAttribute("message", e.getError());
            return new ModelAndView(new RedirectView("/sale/add", true, false, true));
        }
        model.addAttribute("message", "激活邮件已发送至" + email);
        return new ModelAndView(new RedirectView("/sale/add", true, false, true));
    }

    /**
     * 激活页面
     *
     * @param auth
     * @param model
     * @return
     */
    @GetMapping("/activate")
    @PreAuthorize("permitAll()")
    public Object activatePage(Auth auth, Model model) {
        model.addAttribute("token", auth.getToken());
        model.addAttribute("email", auth.getEmail());
        auth.setType(AuthTypeEnum.ACTIVATION.getValue());
        if (!authService.validate(auth)) {
            model.addAttribute("message", "该链接已失效。");
        }
        return "sale-activation";
    }

    /**
     * 激活
     *
     * @param saleActivation
     * @param model
     * @return
     */
    @PostMapping("/activate")
    @PreAuthorize("permitAll()")
    public Object activate(SaleActivation saleActivation, RedirectAttributes model) {
        ValidateUtil.min(saleActivation.getUser().getPassword(), 6);
        ValidateUtil.isNull(saleActivation.getUserSale().getCategoryNumber());
        ValidateUtil.isNull(saleActivation.getUserSale().getImageKey());
        ValidateUtil.in(saleActivation.getUserSale().getStatus(), null, SaleStatusEnum.BUSINESS.getValue(), SaleStatusEnum.REST.getValue());
        ValidateUtil.isNull(saleActivation.getUserSale().getSalesVolume());
        ValidateUtil.isNull(saleActivation.getUserSale().getScore1Number());
        ValidateUtil.isNull(saleActivation.getUserSale().getScore2Number());
        ValidateUtil.isNull(saleActivation.getUserSale().getScore3Number());
        ValidateUtil.isNull(saleActivation.getUserSale().getScorePersonNumber());
        ValidateUtil.isNull(saleActivation.getUserSale().getScoreTotal());

        Auth auth = saleActivation.getAuth();
        auth.setType(AuthTypeEnum.ACTIVATION.getValue());
        User user = saleActivation.getUser();

        user.setEmail(auth.getEmail());
        user.setRole(RoleEnum.SALE.getValue());
        UserSale userSale = saleActivation.getUserSale();

        CutUserSale cutUserSale = new CutUserSale();
        cutUserSale.setUser(user);
        cutUserSale.setUserSale(userSale);

        if (!authService.validate(auth)) {
            return new ModelAndView(new RedirectView("activate", true, false, true));
        }
        userSaleService.addSale(cutUserSale, auth);
        model.addAttribute("message", "账号（" + auth.getEmail() + "）已成功激活。");
        return new ModelAndView(new RedirectView("/login", true, false, true));
    }

    /**
     * 商家详情页面
     *
     * @return
     */
    @GetMapping("/own")
    @PreAuthorize("hasRole('ROLE_SALE')")
    public Object detail(@ModelAttribute("message") String message, Model model) {
        long saleId = SecurityUserUtil.getUser().getId();
        CutUserSale cutUserSale = userSaleService.getCutUserSaleByUserId(saleId);
        model.addAttribute("downDomain", qiniuService.getDownDomain());
        model.addAttribute("cutUserSale", cutUserSale);
        model.addAttribute("message", message);
        model.addAttribute("deliveryDiscounts", deliveryDiscountService.getListBySaleId(saleId));
        return "sale-edit";
    }

    /**
     * 商家修改个人信息
     *
     * @param userSale
     * @return
     */
    @PostMapping("/own")
    @PreAuthorize("hasRole('ROLE_SALE')")
    public Object update(UserSale userSale, RedirectAttributes model) {
        ValidateUtil.isNull(userSale.getImageKey());
        ValidateUtil.isNull(userSale.getCategoryNumber());
        ValidateUtil.in(userSale.getStatus(), null, SaleStatusEnum.BUSINESS.getValue(), SaleStatusEnum.REST.getValue());
        ValidateUtil.isNull(userSale.getSalesVolume());
        ValidateUtil.isNull(userSale.getScore1Number());
        ValidateUtil.isNull(userSale.getScore2Number());
        ValidateUtil.isNull(userSale.getScore3Number());
        ValidateUtil.isNull(userSale.getScorePersonNumber());
        ValidateUtil.isNull(userSale.getScoreTotal());

        long saleId = SecurityUserUtil.getUser().getId();
        userSale.setUserId(saleId);
        userSaleService.updateUserSale(userSale);
        model.addAttribute("message", "修改成功。");
        return new ModelAndView(new RedirectView("own", true, false, true));
    }

    /**
     * 密码修改页面
     *
     * @param message
     * @param model
     * @return
     */
    @GetMapping("/own/modifyPsd")
    @PreAuthorize("hasRole('ROLE_SALE')")
    public Object modifyPsdPage(@ModelAttribute("message") String message, Model model) {
        model.addAttribute("message", message);
        return "sale-psd-modify";
    }

    /**
     * 修改密码
     *
     * @return
     */
    @PostMapping("/own/modifyPsd")
    @PreAuthorize("hasRole('ROLE_SALE')")
    public Object modifyPsd(String oldPassword, String newPassword, RedirectAttributes model, HttpServletRequest request) {
        ValidateUtil.min(newPassword, 6);
        User user = SecurityUserUtil.getUser();
        if (!userService.validatePsd(user, oldPassword)) {
            model.addAttribute("message", "旧密码错误！");
            return new ModelAndView(new RedirectView("/sale/own/modifyPsd", true, false, true));
        }
        if (oldPassword.equals(newPassword)) {
            model.addAttribute("message", "新旧密码不能相同！");
            return new ModelAndView(new RedirectView("/sale/own/modifyPsd", true, false, true));
        }
        userService.updatePsd(user.getEmail(), newPassword);
        request.getSession().invalidate();//清空session
        model.addAttribute("message", "密码已修改，请重新登录。。");
        return new ModelAndView(new RedirectView("/login", true, false, true));
    }

    /**
     * 获取封面图片修改token
     *
     * @return
     */
    @GetMapping("/own/coverToken")
    @PreAuthorize("hasRole('ROLE_SALE')")
    @ResponseBody
    public Object coverToken() {
        long saleId = SecurityUserUtil.getUser().getId();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uptoken", qiniuService.buildSaleCoverToken(saleId));
        return jsonObject.toJSONString();
    }

    /**
     * 封面图上传成功，七牛回调。
     *
     * @param saleId
     * @return
     */
    @PostMapping("/{saleId}/coverImage")
    @PreAuthorize("permitAll()")
    @ResponseBody
    public Object coverImage(@PathVariable(name = "saleId") long saleId) {
        CutUserSale cutUserSale = userSaleService.getCutUserSaleByUserId(saleId);
        String oldCoverImageKey = cutUserSale.getUserSale().getImageKey();
        if (!StringUtils.isEmpty(oldCoverImageKey) && !qiniuService.deleteKey(oldCoverImageKey)) {
            throw new RuntimeException("老图删除失败！");
        }
        String imageKey = qiniuService.buildImageKey();
        UserSale userSale = new UserSale();
        userSale.setUserId(saleId);
        userSale.setImageKey(imageKey);
        userSaleService.updateUserSale(userSale);
        return AjaxQiniuMessage.newSuccess(imageKey, AjaxMessage.newSuccessMsg(imageKey)).toJsonString();
    }

    @PostMapping("/own/deliveryDiscount")
    @PreAuthorize("hasRole('ROLE_SALE')")
    @ResponseBody
    public Object addDeliveryDiscount(DeliveryDiscount deliveryDiscount) {
        long saleId = SecurityUserUtil.getUser().getId();
        ValidateUtil.notNull(deliveryDiscount.getFull());
        ValidateUtil.notNull(deliveryDiscount.getDeliveryPrice());
        deliveryDiscount.setSaleId(saleId);
        try {
            userSaleService.addDeliveryDiscount(deliveryDiscount);
        } catch (XmbException e) {
            return AjaxMessage.newErrorHintMsg(e.getError());
        }
        return AjaxMessage.newSuccessMsg(deliveryDiscount);
    }

    @PostMapping("/own/deliveryDiscount/{deliveryDiscountId}/delete")
    @PreAuthorize("hasRole('ROLE_SALE')")
    @ResponseBody
    public Object removeDeliveryDiscount(@PathVariable(name = "deliveryDiscountId") long deliveryDiscountId) {
        long saleId = SecurityUserUtil.getUser().getId();
        try {
            userSaleService.removeDeliveryDiscount(saleId, deliveryDiscountId);
        } catch (XmbException e) {
            return AjaxMessage.newErrorHintMsg(e.getError());
        }
        return AjaxMessage.newSuccessMsg();
    }
}
